//
//  TPDestinationViewController.m
//  TravelProject
//
//  Created by lanou3g on 15/11/23.
//  Copyright © 2015年 韩婷婷. All rights reserved.
//

#import "TPDestinationViewController.h"
#import "TPFavoriteDestinationCell.h"
#import "TPOtherDestinationCell.h"
#import "DestinationReusable.h"
#import "HT_DataDownloadTools.h"
#import "CountryModel.h"



@interface TPDestinationViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet UICollectionViewFlowLayout *destinationLayout;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

//存储数据
@property (nonatomic,strong) NSMutableDictionary *dataDic;
//标志位
@property (nonatomic,copy ) NSString  *flag;

@end

@implementation TPDestinationViewController

+(instancetype)shareDestinationVC{
    static TPDestinationViewController *destinationVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        //获取playerVC实例
        destinationVC = [mainStoryboard instantiateViewControllerWithIdentifier:@"destination"];
    });
    return destinationVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _flag =@"亚洲";
    [self setupCollectionView];
    [self setupButtonClick];
    [self requestData];
    
    
    // Do any additional setup after loading the view from its nib.
}
- (void)requestData{
    NSDate *date = [NSDate date];
    NSTimeInterval timeInterval =[date timeIntervalSince1970];
   [HT_DataDownloadTools downloadDataWithURL:[NSString stringWithFormat:@"http://open.qyer.com/qyer/footprint/continent_list?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=865308021990677&track_app_version=6.8.2&track_app_channel=hicloud&track_device_info=hwH30-T00&track_os=Android4.2.2&app_installtime=%.0f&lat=40.030155&lon=116.343631",timeInterval * 1000] andMethod:@"get" andBody:nil andBlock:^(NSData *data) {
       [self solveData:data];
       [self.collectionView reloadData];
   }];
}
- (void)solveData:(NSData *)data{
    NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
    self.dataDic = [NSMutableDictionary dictionary];
    NSArray *array = dictionary[@"data"];
    for (NSDictionary *dic in array) {
        NSString *key = dic[@"cnname"];
        NSArray *arr = dic[@"hot_country"];
        NSMutableArray *mArray = [NSMutableArray array];
        for (NSDictionary *d in arr) {
            CountryModel *model = [[CountryModel alloc]init];
            [model setValuesForKeysWithDictionary:d];
            [mArray addObject:model];
        }
        NSArray *arr2 = dic[@"country"];
        NSMutableArray *mArray2 = [NSMutableArray array];
        for (NSDictionary *d in arr2) {
            CountryModel *model = [[CountryModel alloc]init];
            [model setValuesForKeysWithDictionary:d];
            [mArray2 addObject:model];
        }
        NSArray *a = @[mArray,mArray2];
        [self.dataDic setObject:a forKey:key];
    }
}
//加载collectionView
- (void)setupCollectionView{
   _destinationLayout.itemSize = CGSizeMake((CGRectGetWidth([UIScreen mainScreen].bounds)-100)/3, 300);
   _destinationLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    UINib *nib1 = [UINib nibWithNibName:@"TPFavoriteDestinationCell" bundle:[NSBundle mainBundle]];
    UINib *nib2 = [UINib nibWithNibName:@"TPOtherDestinationCell" bundle:[NSBundle mainBundle]];
    UINib *nib3 = [UINib nibWithNibName:@"DestinationReusable" bundle:[NSBundle mainBundle]];
    [self.collectionView registerNib:nib1 forCellWithReuseIdentifier:@"favorite"];
    [self.collectionView registerNib:nib2 forCellWithReuseIdentifier:@"other"];
    [self.collectionView registerNib:nib3 forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
}
//提取出7个Button
- (void)setupButtonClick{
    int count = 101;
    for (int i = 0; i < 7; i ++) {
        UIButton *button = (UIButton *)[self.view viewWithTag:count++];
        [button addTarget:self action:@selector(didClickButtonChose:) forControlEvents:UIControlEventTouchUpInside];
    }
}
//Button点击事件
- (void)didClickButtonChose:(UIButton *)sender{
    int count = 101;
    for (int i = 0; i < 7; i ++) {
        UIButton *button = (UIButton *)[self.view viewWithTag:count++];
        button.backgroundColor = [UIColor cyanColor];
    }
    sender.backgroundColor = [UIColor greenColor];
    _flag = sender.titleLabel.text;
    [self.collectionView reloadData];
}

#pragma mark --- collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSInteger a = [self.dataDic[_flag][0] count];
    NSInteger b = [self.dataDic[_flag][1] count];
    self.scrollView.contentSize = CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds), 310 * (a/2 + a%2) +180 +150 + 80 * (b/2 +b%2));
    if (section == 0) {
        
        return a;
    }
    return b;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 2;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        TPFavoriteDestinationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"favorite" forIndexPath:indexPath];
        //cell.backgroundColor = [UIColor redColor];
        CountryModel *m = self.dataDic[_flag][0][indexPath.row];
        cell.model = m;
        return cell;
    }else{
        TPOtherDestinationCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"other" forIndexPath:indexPath];
        cell.backgroundColor = [UIColor whiteColor];
        CountryModel *m = self.dataDic[_flag][1][indexPath.row];
        cell.model = m;
        return cell;
    }
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
      return  CGSizeMake((CGRectGetWidth([UIScreen mainScreen].bounds)-60)/2, 300);
    }
    else{
     return CGSizeMake((CGRectGetWidth([UIScreen mainScreen].bounds)-60)/2, 70);
    }
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    DestinationReusable *cell = (DestinationReusable *)[collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        if ([self.dataDic[_flag][0] count] > 0 ) {
            cell.label.text = [NSString stringWithFormat:@"%@热门目的地",_flag];
        }else{
            cell.label.text = nil;
        }
        
    }else{
        if ([self.dataDic[_flag][1] count] > 0 ) {
          cell.label.text = [NSString stringWithFormat:@"%@其他目的地",_flag];
        }else{
            cell.label.text = nil;
        }
    }
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
